package com.three.domain.mail;

import com.fasterxml.jackson.core.type.TypeReference;
import com.three.base.AbstractEntity;
import com.three.config.LanguageConfig;
import com.three.constant.LanguageId;
import com.three.constant.MailConstants;
import com.three.db.idService.IdService;
import com.three.exception.GameException;
import com.three.repository.MailRepository;
import com.three.reward.RewardItem;
import com.three.reward.RewardList;
import com.three.utils.JsonUtils;
import com.three.utils.SpringUtils;
import com.three.utils.StringUtils;
//import com.three.utils.WordsFilterUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.util.Date;
import java.util.List;

/**
 * Created by Mathua on 2017/6/22.
 */
@Entity
@Table(name = "t_mail")
public class MailPo extends AbstractEntity {
    private static final Logger LOGGER = LoggerFactory.getLogger(MailPo.class);

    @Id
    private long id;
    @Column(name = "receiver_id")
    private long receiverId;// 接收者id
    @Column(name = "mail_type")
    private int mailType;// 邮件类型
    @Column(name = "subject", nullable = false)
    private String subject;// 邮件主题
    @Column(name = "content", nullable = false)
    private String content;// 邮件内容
    @Column(name = "items_json")
    private String itemsJson;// 物品的json数据
    @Column(name = "is_recommend")
    private boolean isRecommend;// 是否为推荐
    @Column(name = "send_time", nullable = false)
    private Date sendTime;// 发送时间
    @Column(name = "delete_time")
    private Date deleteTime;// 删除时间
    @Column(name = "had_read")
    private boolean hadRead;// 是否已阅读
    @Column(name = "had_send")
    private boolean hadSend;// 是否已发送

    /**
     * 阅读邮件
     */
    public void read() throws GameException {
        // 已读
        if(hadRead && getMailType() != MailType.ITEMS_MAIL) {
            LOGGER.error("mail had read.mail id={}", id);
            throw new GameException(LanguageConfig.getText(LanguageId.HAD_READ_MAIL));
        }
        // 领取附件
        if(getMailType() == MailType.ITEMS_MAIL && itemsJson != null) {
            List<RewardItem> rewards = JsonUtils.fromJson(itemsJson, new TypeReference<List<RewardItem>>() {
            }.getType());
            if(rewards != null && !rewards.isEmpty()) {
                RewardList rewardList = RewardList.valueOf(rewards, receiverId);
                rewardList.handOutReward(false);
            }
        }
        hadRead = true;
        SpringUtils.getBean(MailRepository.class).save(this);
    }

    /**
     * 构建一封邮件
     *
     * @param receiverId  接收者id
     * @param subject     主题
     * @param content     内容
     * @param items       附件
     * @param isRecommend 是否是推荐
     * @param sendTime    发送时间(可以是未来某个时间，则定时发送)
     * @param deleteTime  删除时间
     * @return
     */
    public static MailPo build(long receiverId, String subject, String content, List<RewardItem> items, boolean isRecommend, Date sendTime, Date deleteTime) throws GameException {
        // 检查数据
        MailType mailType;
        if(subject == null)
            subject = StringUtils.EMPTY;
        if(content == null)
            content = StringUtils.EMPTY;
        if(items == null || items.isEmpty())
            mailType = MailType.PLAIN_TEXT;
        else
            mailType = MailType.ITEMS_MAIL;
        if(sendTime == null)
            sendTime = new Date();
        if(subject.length() > MailConstants.SUBJECT_LIMIT) {
            throw new GameException(LanguageConfig.getText(LanguageId.OVER_MAIL_SUBJECT_LIMIT));
        }
        if((mailType == MailType.PLAIN_TEXT && content.length() > MailConstants.CONTENT_LIMIT_FOR_PLAIN_TEXT) || content.length() > MailConstants.CONTENT_LIMIT_FOR_ITEMS_MAIL) {
            throw new GameException(LanguageConfig.getText(LanguageId.OVER_MAIL_CONTENT_LIMIT));
        }
        // 敏感词过滤
//        subject = WordsFilterUtils.filterWords(subject);
//        content = WordsFilterUtils.filterWords(content);

        MailPo mailPo = new MailPo();
        mailPo.id = IdService.get().get();
        mailPo.receiverId = receiverId;
        mailPo.mailType = mailType.getId();
        mailPo.subject = subject;
        mailPo.content = content;
        mailPo.itemsJson = JsonUtils.toJson(items);
        mailPo.isRecommend = isRecommend;
        mailPo.sendTime = sendTime;
        mailPo.deleteTime = deleteTime;
        mailPo.hadRead = false;
        mailPo.hadSend = false;
        return mailPo;
    }

    public void setHadSend() {
        hadSend = true;
        SpringUtils.getBean(MailRepository.class).save(this);
    }

    @Override
    public long getEntityId() {
        return id;
    }

    public long getReceiverId() {
        return receiverId;
    }

    public MailType getMailType() {
        return MailType.valueOf(mailType);
    }

    public String getSubject() {
        return subject;
    }

    public String getContent() {
        return content;
    }

    public String getItemsJson() {
        return itemsJson;
    }

    public boolean isRecommend() {
        return isRecommend;
    }

    public Date getSendTime() {
        return sendTime;
    }

    public Date getDeleteTime() {
        return deleteTime;
    }

    public boolean isHadRead() {
        return hadRead;
    }

    public boolean isHadSend() {
        return hadSend;
    }

    @Override
    public String toString() {
        return "MailPo{" +
                "id=" + id +
                ", receiverId=" + receiverId +
                ", mailType=" + mailType +
                ", subject='" + subject + '\'' +
                ", content='" + content + '\'' +
                ", itemsJson='" + itemsJson + '\'' +
                ", isRecommend=" + isRecommend +
                ", sendTime=" + sendTime +
                ", deleteTime=" + deleteTime +
                ", hadRead=" + hadRead +
                ", hadSend=" + hadSend +
                '}';
    }
}
